package blue.http.internal.core.net.render;

import blue.base.core.util.AssertUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.CharArrayWriter;
import java.util.Map;

/**
 * @author Jin Zheng
 * @since 1.0 2021-08-12
 */
public class FreeMarkerRender implements Render {
	private static Logger logger = LoggerFactory.getLogger(FreeMarkerRender.class);

	public static final String FTL_EXT = ".ftl";
	private final Configuration config;

	public FreeMarkerRender(String root) {
		AssertUtil.notEmpty(root, "Root Path");
		config = new Configuration(Configuration.VERSION_2_3_31);
		config.setClassLoaderForTemplateLoading(Thread.currentThread().getContextClassLoader(), root);
		this.initConfig();
		logger.info("FreeMarker root path: {}", root);
	}

	private void initConfig() {
		config.setDefaultEncoding("UTF-8");

		try {
			config.setSetting("defaultEncoding", "UTF-8");
			config.setSetting("number_format", "#.##");
			config.setSetting("datetime_format", "yyyy-MM-dd HH:mm");
			config.setSetting("date_format", "yyyy-MM-dd");
			config.setSetting("time_format", "HH:mm:ss");
		} catch (TemplateException e) {
			logger.warn("FreeMarker initialize error, ", e);
		}
	}

	@Override
	public String render(String view, Map<String, Object> param) {
		String html = null;
		try (CharArrayWriter writer = new CharArrayWriter()) {
			Template template = config.getTemplate(view + FTL_EXT);
			template.process(param, writer);
			html = writer.toString();
		} catch (Exception e) {
			logger.error("FreeMarker render error: " + view, e);
		}
		return html;
	}
}
